<template>
    <div class="content customer-page">
        <div>
            <h3>客户信息</h3>
            <section>
                <Form
                    ref="customForm"
                    id="custom_form"
                    :model="customInfo"
                    :rules="customRules"
                    inline
                    :labelWidth="100"
                >
                    <FormItem prop="custName" label="企业名称">
                        <Input :disabled="disabled" class="ipt-w" v-model="customInfo.custName"></Input>
                    </FormItem>
                    <FormItem prop="custLocation" label="企业所在地">
                        <Select
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.custLocation"
                            placeholder="请选择企业所在地"
                            filterable
                        >
                            <Option
                                v-for="(item, index) in custLocationList"
                                :key="index"
                                :value="item.value"
                                :label="item.value"
                            ></Option>
                        </Select>
                    </FormItem>
                    <FormItem
                        :label="isDomestic ? '海关代码' : '企业AEO代码'"
                        prop="customsCode"
                        :class="domesticClass"
                    >
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model.trim="customInfo.customsCode"
                        ></Input>
                    </FormItem>
                    <FormItem label="检疫代码" prop="ciqCode">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.ciqCode"
                        ></Input>
                    </FormItem>
                    <FormItem label="组织机构代码" prop="copCode">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.copCode"
                        ></Input>
                    </FormItem>
                    <FormItem label="企业中文地址" prop="addressCn">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.addressCn"
                        ></Input>
                    </FormItem>
                    <FormItem label="企业英文名称" prop="custNameEn" :class="overseasClass">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.custNameEn"
                        ></Input>
                    </FormItem>
                    <FormItem label="企业英文地址" prop="addressEn">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.addressEn"
                        ></Input>
                    </FormItem>
                    <FormItem label="电话号码" prop="phone">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.phone"
                        ></Input>
                    </FormItem>
                    <FormItem label="传真" prop="fax">
                        <Input :disabled="disabled" class="ipt-w" v-model="customInfo.fax"></Input>
                    </FormItem>
                    <FormItem label="开户行" prop="depositBank">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.depositBank"
                        ></Input>
                    </FormItem>
                    <FormItem label="银行账户" prop="bankAccount">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.bankAccount"
                        ></Input>
                    </FormItem>
                    <FormItem label="企业类型" prop="custType" :class="domesticClass">
                        <Select
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.custType"
                            placeholder="请选择企业类型"
                            filterable
                            clearable
                            @keyup.enter.native="handleCustTypeEnter"
                        >
                            <Option
                                v-for="(item, index) in custTypeList"
                                :key="index"
                                :value="item.value"
                                :label="item.value"
                            ></Option>
                        </Select>
                    </FormItem>
                    <FormItem label="信用代码" prop="socialCreditCode" :class="domesticClass">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.socialCreditCode"
                        ></Input>
                    </FormItem>
                    <FormItem label="备注" prop="remark">
                        <Input
                            :disabled="disabled"
                            class="ipt-w"
                            v-model="customInfo.remark"
                        ></Input>
                    </FormItem>
                </Form>
            </section>
            <BusinessUnit :disabled="disabled" ref="busniess" />
            <footer class="submit-footer">
                <Button
                    :disabled="disabled"
                    type="primary"
                    @click="submit"
                    :loading="sbLoading"
                >保存</Button>
                <Button @click="cancel">取消</Button>
            </footer>
        </div>
    </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { focusIndexInput, nextFocus } from '@/libs/ivuDom'
import { on } from '@/libs/tools'
import { editCustom, addCustom, queryCustomById } from '@/api/customer'
import BusinessUnit from './components/business-unit'
import rules from './js/customRules'
import { isEditPage } from '@/libs/changeTips'

export default {
    name: 'NewCustomer',
    inject: ['nextPageReload'],
    props: {
        disabled: {
            type: Boolean,
            default: false
        }
    },
    components: {
        BusinessUnit
    },
    data () {
        // 检查海关编码
        const checkCustomsCode = (rule, value, callback) => {
            if (this.isDomestic) {
                rules.customsCode(
                    this.customInfo.custId,
                    rule,
                    value,
                    callback
                )
            } else {
                if (value && (value.length < 4 || value.length > 40)) {
                    callback(new Error('企业AEO代码长度为4-40个字符'))
                } else {
                    callback()
                }
            }
        }
        // 检查企业类型
        const checkCustType = (rule, value, callback) => {
            this.isDomestic
                ? value
                    ? callback()
                    : callback('请选择企业类型')
                : callback()
        }
        // 检查企业英文名
        const checkCustNameEn = (rule, value, callback) => {
            this.isDomestic
                ? callback()
                : value
                    ? callback()
                    : callback('请输入企业英文名')
        }
        return {
            tabName: 'data',
            customRules: {
                custName: [
                    {
                        required: true,
                        message: '企业名称不能为空',
                        trigger: 'blur'
                    },
                    {
                        type: 'string',
                        max: 50,
                        message: '企业名称最大长度50个字符',
                        trigger: 'blur'
                    }
                ],
                custLocation: [
                    {
                        required: true,
                        message: '请选择企业所在地',
                        trigger: 'blur'
                    }
                ],
                customsCode: [{ validator: checkCustomsCode, trigger: 'blur' }],
                custType: [{ validator: checkCustType, trigger: 'blur' }],
                socialCreditCode: [
                    {
                        required: true,
                        message: '统一社会信用代码必填',
                        trigger: 'blur'
                    },
                    {
                        type: 'string',
                        min: 18,
                        max: 18,
                        message: '统一社会信用代码长度18个字符',
                        trigger: 'blur'
                    }
                ],
                ciqCode: [
                    {
                        type: 'string',
                        min: 10,
                        max: 10,
                        message: '检疫检验编码长度10个字符',
                        trigger: 'blur'
                    }
                ],
                copCode: [
                    {
                        type: 'string',
                        max: 20,
                        message: '组织机构代码最大长度20个字符',
                        trigger: 'blur'
                    }
                ],
                addressCn: [
                    {
                        type: 'string',
                        max: 100,
                        message: '企业地址最大长度100个字符',
                        trigger: 'blur'
                    }
                ],
                custNameEn: [
                    {
                        type: 'string',
                        max: 100,
                        message: '企业英文名称最大长度100个字符',
                        trigger: 'blur'
                    },
                    {
                        validator: checkCustNameEn,
                        trigger: 'blur'
                    }
                ],
                addressEn: [
                    {
                        type: 'string',
                        max: 500,
                        message: '公司英文地址最大长度500个字符',
                        trigger: 'blur'
                    }
                ],
                phone: [
                    {
                        type: 'string',
                        max: 20,
                        validator: rules.phone(),
                        trigger: 'blur'
                    }
                ],
                fax: [
                    {
                        type: 'string',
                        max: 20,
                        message: '传真最大长度20个字符',
                        trigger: 'blur'
                    }
                ],
                depositBank: [
                    {
                        type: 'string',
                        max: 100,
                        message: '开户行最大长度100个字符',
                        trigger: 'blur'
                    }
                ],
                bankAccount: [
                    {
                        type: 'string',
                        max: 25,
                        validator: rules.bankAccount(),
                        trigger: 'blur'
                    }
                ],
                remark: [
                    {
                        type: 'string',
                        max: 200,
                        message: '备注长度200个字符以内',
                        trigger: 'blur'
                    }
                ]
            },
            customInfo: {
                // 客户信息
                custId: '', // 客户id
                custName: '', // 企业名称
                custLocation: '境内企业', // 企业所在地
                customsCode: '', // 海关编号
                custType: '', // 企业类型
                socialCreditCode: '', // 统一社会信用代码
                ciqCode: '', // 检验检疫编码
                copCode: '', // 组织机构代码
                addressCn: '', // 企业地址
                custNameEn: '', // 企业英文名称
                addressEn: '', // 企业英文地址
                phone: '', // 电话
                fax: '', // 传真
                depositBank: '', // 开户行
                bankAccount: '', // 银行账号
                remark: '' // 备注
            },
            custLocationList: [{ value: '境内企业' }, { value: '境外企业' }],
            // 企业类型
            custTypeList: [
                { value: '生产企业' },
                { value: '报关行' },
                { value: '供应链公司' },
                { value: '货代公司' },
                { value: '船代' },
                { value: '其他' }
            ],
            sbLoading: false
        }
    },
    computed: {
        // 是否为国内
        isDomestic () {
            return this.customInfo.custLocation == '境内企业'
        },
        // 国内form label class
        domesticClass () {
            return this.isDomestic ? 'ivu-form-item-required' : ''
        },
        // 国外form label class
        overseasClass () {
            return this.isDomestic ? '' : 'ivu-form-item-required'
        }
    },
    mounted () {
        const id = this.$route.params.id
        id && this.queryCustomInfo(id)
        this.$nextTick(_ => {
            this.bindFormInputCutover()
        })
    },
    activated () {
        this.$nextTick(_ => {
            this.inputs && focusIndexInput(0, this.inputs)
        })
    },
    methods: {
        ...mapMutations(['removeTagNav']),
        // 查询公司信息
        queryCustomInfo (id) {
            queryCustomById({ id }).then(res => {
                if (res.data.code === '0000') {
                    const data = res.data.data || {}
                    Object.keys(this.customInfo).forEach(key => {
                        this.customInfo[key] = data[key] || ''
                    })
                    this.$refs.busniess.setData(data.unitList)
                } else {
                    this.$Message.warning(res.data.msg)
                }
            })
        },
        // 绑定公司信息表单input回车切换
        bindFormInputCutover () {
            const formDom = document.getElementById('custom_form')
            this.inputs = formDom.querySelectorAll('input[type=text]')
            const self = this
            on(formDom, 'keyup', function next (event) {
                if (event.keyCode === 13) {
                    nextFocus(event, self.inputs)
                }
            })
        },
        // 处理企业类型select回车事件
        handleCustTypeEnter () {
            if (!this.customInfo.custType) {
                this.customInfo.custType = this.custTypeList[0].value
            }
        },
        async submit () {
            this.sbLoading = true
            const bv = await this.$refs.busniess.validate()
            if (!bv) {
                this.tabName = 'data'
                this.sbLoading = false
                return this.$Message.warning('请保存经营单位数据')
            }
            const cv = await this.$refs.customForm.validate()
            if (!cv) {
                this.sbLoading = false
                return
            }
            const data = {
                ...this.customInfo
            }
            data.quoteList = []
            data.unitList = this.$refs.busniess.getData()
            const postFn = this.customInfo.custId ? editCustom : addCustom
            postFn(data)
                .then(res => {
                    if (res.data.code === '0000') {
                        this.$Message.success(res.data.msg)
                        this.nextPageReload()
                        this.goBack()
                    } else {
                        this.$Message.warning(res.data.msg)
                    }
                    this.sbLoading = false
                })
                .catch(err => {
                    this.$Message.error('保存失败')
                    this.sbLoading = false
                })
        },
        goBack () {
            this.removeTagNav(this.$route)
            this.$router.push({
                name: 'customerList'
            })
        },
        cancel () {
            const fullPath = this.$route.fullPath
            if (!this.disabled && isEditPage(fullPath)) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '这个页面还有数据没有保存，请确认是否直接关闭？',
                    onOk: () => {
                        this.goBack()
                    }
                })
            } else {
                this.goBack()
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import './less/customer';
.ipt-w {
    width: 200px;
}
.require-label {
    margin-right: 4px;
    font-family: SimSun;
    font-size: 12px;
    color: #ed4014;
}
</style>
